package library;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.ArrayList;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;

import database_objects.Department;

import user_client.LibrarianUserClient;

public class DepartmentManagerPane extends JPanel {

	private JDialog owner = null;
	private Integer idOfDepartment = null;
	private String name = "";
	private Integer bookCaseNumber = null;

	private Integer idOfDepartmentTemp = null;
	private String nameTemp = "";
	private Integer bookCaseNumberTemp = null;

	private String names[] = new String[3];
	private TextPane dataPane = null;
	private JTable results;
	private JLabel labelResult = new JLabel("nie wybrano działu...");

	private NumberFormat bookCaseNumberFormat;
	private LibrarianUserClient client = null;

	private DefaultTableModel model = new DefaultTableModel();

	public DepartmentManagerPane(LibrarianUserClient client,
			Integer idOfDepartment, String name, JPanel mainArea, 
				JDialog owner) {
		this.owner = owner;
		this.setPreferredSize(new Dimension(300, 200));

		model.addColumn("id działu");
		model.addColumn("nazwa");
		model.addColumn("nr regału");

		results = new JTable(model);
		results.setOpaque(true);

		results.getSelectionModel().addListSelectionListener(
				new MySelectionListener());

		this.client = client;
		initComponents();
	}

	private void initComponents() {
		this.setLayout(new GridBagLayout());

		names[0] = "nazwa";
		names[1] = "numer regału";

		dataPane = new TextPane(names, new JTextField(),
				new JFormattedTextField(bookCaseNumberFormat));

		AgreeButton button1 = new AgreeButton("Zatwierdź");
		CloseButton button2 = new CloseButton("Anuluj");
		AddButton addButton = new AddButton("dodaj dział");
		RemoveButton removeButton = new RemoveButton("usuń dział");
		SearchButton searchButton = new SearchButton("Znajdź");
		JScrollPane scroll = new JScrollPane(results);
		scroll.setPreferredSize(new Dimension(200, 150));

		// scroll
		GridBagConstraints scrollConstraints = new GridBagConstraints();
		scrollConstraints.fill = GridBagConstraints.HORIZONTAL;
		scrollConstraints.gridx = 1;
		scrollConstraints.gridy = 0;
		scrollConstraints.gridwidth = 2;
		scrollConstraints.gridheight = 10;

		// text pane
		GridBagConstraints textPaneConstraints = new GridBagConstraints();

		textPaneConstraints.gridx = 0;
		textPaneConstraints.gridy = 0;

		textPaneConstraints.gridheight = 4;

		// button search
		GridBagConstraints searchConstraints = new GridBagConstraints();
		searchConstraints.fill = GridBagConstraints.HORIZONTAL;
		searchConstraints.gridx = 0;
		searchConstraints.gridy = 5;

		// button add
		GridBagConstraints addConstraints = new GridBagConstraints();
		addConstraints.fill = GridBagConstraints.HORIZONTAL;
		addConstraints.gridx = 0;
		addConstraints.gridy = 6;

		// button remove
		GridBagConstraints removeConstraints = new GridBagConstraints();
		removeConstraints.fill = GridBagConstraints.HORIZONTAL;

		removeConstraints.gridx = 0;
		removeConstraints.gridy = 7;

		GridBagConstraints buttonsConstraints = new GridBagConstraints();

		buttonsConstraints.gridx = 1;
		buttonsConstraints.gridy = 13;

		GridBagConstraints abortConstraints = new GridBagConstraints();

		abortConstraints.gridx = 2;
		abortConstraints.gridy = 13;

		GridBagConstraints labelConstraints = new GridBagConstraints();
		labelConstraints.gridx = 1;
		labelConstraints.gridy = 12;
		labelConstraints.gridwidth = 2;

		this.add(labelResult, labelConstraints);
		this.add(scroll, scrollConstraints);
		this.add(addButton, addConstraints);
		this.add(removeButton, removeConstraints);
		this.add(searchButton, searchConstraints);
		this.add(dataPane, textPaneConstraints);
		this.add(button1, buttonsConstraints);
		this.add(button2, abortConstraints);

	}

	private void setUpFormats() {
		// TODO
	}

	private class AgreeButton extends JButton implements ActionListener {

		public AgreeButton(String text) {
			super(text);
			this.addActionListener(this);
			// this.setPreferredSize(new Dimension(400,100));
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			idOfDepartment  = idOfDepartmentTemp;
			name = nameTemp;
			bookCaseNumber = bookCaseNumberTemp;
			owner.dispose();
			
		}
	}

	private class CloseButton extends JButton implements ActionListener {

		public CloseButton(String text) {
			super(text);
			this.addActionListener(this);
			
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			// TODO Auto-generated method stub
			owner.dispose();
		}
	}

	private class SearchButton extends JButton implements ActionListener {

		public SearchButton(String text) {
			super(text);
			this.addActionListener(this);

		}

		@Override
		public void actionPerformed(ActionEvent e) {

			try {
				ArrayList<Department> departments = client.searchDepartments(
						dataPane.getField("nazwa").getText(), dataPane
								.getField("numer regału").getText());

				while (DepartmentManagerPane.this.model.getRowCount() > 0) {
					try {
						DepartmentManagerPane.this.model.removeRow(0);
					} catch (Exception a) {
						System.out.println("ERRRORRRRRRRR????");
					}

				}

				for (Department dep : departments) {
					System.out.println(dep.getName());
					String[] val = new String[3];
					val[0] = dep.getId();
					val[1] = dep.getName();
					val[2] = dep.getBookCaseNumber();
					DepartmentManagerPane.this.model.addRow(val);
				}

				results.revalidate();
				results.repaint();

			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}

	private class AddButton extends JButton implements ActionListener {

		public AddButton(String text) {
			super(text);
			// this.setPreferredSize(new Dimension(200,70));
			this.addActionListener(this);
			// this.setPreferredSize(new Dimension(400,100));
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			String name = dataPane.getField("nazwa").getText();
			// String numberOfPane = dataPane.
			String numberOfCaseLocal = dataPane.getField("numer regału")
					.getText();

			if ((name.length() > 0) && (name != "")
					&& (numberOfCaseLocal != "")
					&& (numberOfCaseLocal.length() > 0)) {

				try {
					Integer index = client.addDepartment(name,
							numberOfCaseLocal);
					if (index != -1) {
						System.out.println("INDEX:" + index);
						String[] newRow = new String[3];
						newRow[0] = index.toString();
						newRow[1] = name;
						newRow[2] = numberOfCaseLocal;
						DepartmentManagerPane.this.model.addRow(newRow);
						DepartmentManagerPane.this.model.fireTableDataChanged();
						results.revalidate();
						results.repaint();

						labelResult.setText("Dodano element");
					} else {
						labelResult.setText("Podany dział już istnieje");
					}
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}

			}
		}
	}

	private class RemoveButton extends JButton implements ActionListener {

		public RemoveButton(String text) {
			super(text);
			this.addActionListener(this);
			// this.setPreferredSize(new Dimension(400,100));
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			try {
				if (idOfDepartment != null) {
					client.removeElement(idOfDepartment.toString(), "dzialy",
							"id_dzialu");
				}
				int i = 0;
				// Integer size =
				// DepartmentManagerPane.this.model.getRowCount();

				while (i < DepartmentManagerPane.this.model.getRowCount()) {
					Integer valS = Integer.valueOf((String) results.getValueAt(
							i, 0));

					if (Integer.valueOf(valS) == idOfDepartment) {
						DepartmentManagerPane.this.model.removeRow(i);
						DepartmentManagerPane.this.model.fireTableDataChanged();

					}

					// DepartmentManagerPane.this.model.removeRow(0);
					i++;
				}
				results.setModel(DepartmentManagerPane.this.model);
				results.revalidate();
				results.repaint();

			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}

		}
	}

	private class MySelectionListener implements ListSelectionListener {

		@Override
		public void valueChanged(ListSelectionEvent e) {
			// TODO Auto-generated method stub
			try {
				String idString = (String) model.getValueAt(
						results.getSelectedRow(), 0);
				idOfDepartmentTemp = Integer.valueOf(idString);
				nameTemp = (String) model.getValueAt(results.getSelectedRow(),
						1);
				String bookCase = (String) model.getValueAt(
						results.getSelectedRow(), 2);
				bookCaseNumberTemp = Integer.valueOf(bookCase);
				System.out.println(idOfDepartmentTemp + ", " + nameTemp + ", "
						+ bookCaseNumberTemp);

				labelResult.setText(idOfDepartmentTemp + " " + nameTemp + " "
						+ bookCaseNumberTemp);

			} catch (ArrayIndexOutOfBoundsException e1) {
				labelResult.setText("nie wybrano działu");
				idOfDepartment = null;
				name = null;
				bookCaseNumber = null;

			}
		}

	}
}
